package com.wangdao.wechatmall.config;

import com.wangdao.wechatmall.realm.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 重写ModularRealmAuthenticator中的doAuthenticate方法，从而进行realm的一个分发
 *
 * @author ZhangXiao on 2021/7/12
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();
        //对realm来进行分发--通过token中携带的type信息进行分发
        MallToken mallToken= (MallToken) authenticationToken;
        String type = mallToken.getType();
        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm originRealm : originRealms) {
            //先取出realm的名字，再将其变成小写的形式，然后再判断是否含有type
            if(originRealm.getName().toLowerCase().contains(type)){
                realms.add(originRealm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm) realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
